/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-09-24
*/
package com.rzico.market.service;

import com.alibaba.fastjson.JSON;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.plugin.jd.JDServiceUtils;
import com.rzico.core.entity.SysMsgPush;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.service.SysMsgPushService;
import com.rzico.market.entity.MarketOrderApply;
import com.rzico.util.CodeGenerator;
import com.rzico.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.market.mapper.MarketOrderApplyMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 京东订单开票信息业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class MarketOrderApplyService extends BaseServiceImpl<MarketOrderApply, String> {

    @Autowired
    private MarketOrderApplyMapper marketOrderApplyMapper;

    @Autowired
    private SysMsgPushService sysMsgPushService;

    @Override
    public BaseMapper<MarketOrderApply, String> getMapper() {
        return marketOrderApplyMapper;
    }

    /**
     * 查询所有京东商品的sku
     * @return
     */
    public List<String> selectAlljdorderIdList(Map<String, Object> params){
        return marketOrderApplyMapper.selectAlljdorderIdList(params);
    }


    /**
     * 保存京东订单开票信息
     * @param map
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public MarketOrderApply saveMarketOrderApply(Map<String, Object> map){
        MarketOrderApply marketOrderApply = new MarketOrderApply();
        marketOrderApply.setCreateDate(new Date());
        marketOrderApply.setDeleted(false);
        marketOrderApply.setOrderId((Long) map.get("order_id"));
        marketOrderApply.setOrderSn(map.get("order_sn").toString());
        marketOrderApply.setOrderCreateDate((Date) map.get("order_create_date"));
        marketOrderApply.setShippingId((Long) map.get("shipping_id"));
        marketOrderApply.setShippingSn(map.get("shipping_sn").toString());
        marketOrderApply.setShippingSendDate((Date) map.get("shipping_send_date"));
        marketOrderApply.setShippingItemId((Long) map.get("shipping_item_id"));
        marketOrderApply.setJdParentOrder(map.get("jd_parent_order").toString());
        marketOrderApply.setJdOrder(map.get("jd_order").toString());
        marketOrderApply.setInvoicePrice((BigDecimal) map.get("invoice_price"));
        marketOrderApply.setState(false);
        marketOrderApply.setResult(false);
        marketOrderApply.setSupplierId((Long) map.get("supplier_id"));
        marketOrderApply.setEnterpriseId((Long) map.get("enterprise_id"));
        marketOrderApply.setCreateBy("admin");
        marketOrderApplyMapper.insertUseGeneratedKeys(marketOrderApply);
        MarketOrderApply result = super.findById(marketOrderApply.getId());
        return result;
    }

    /**
     * 京东订单申请开票列表
     * @param marketOrderApplyList
     * @return
     */
    public void invoiceSubmit(List<MarketOrderApply> marketOrderApplyList, String marketId, SysPlugin sysplugin){
        String token = JDServiceUtils.refrash_token();
        int allOrderNum = marketOrderApplyList.size();//待申请开票的京东子订单数量
        //计算所有订单的开票金额
        BigDecimal allOrderPrice = new BigDecimal(0);
        for (MarketOrderApply marketOrderApply : marketOrderApplyList) {
            allOrderPrice.add(marketOrderApply.getInvoicePrice());
        }
        //因每次申请开票最多申请500个京东子订单，若京东子订单数大于500要分多批次申请
        if (500 > allOrderNum) {
            jdInvoiceSubmit(marketOrderApplyList, token, 1,1, allOrderPrice.toString(), marketId, sysplugin);
        } else {
            int toIndex = 500;//一次申请500个京东子订单
            int currentBatchNum = 0;//当前批次
            int remainder = allOrderNum % 500;//计算订单数除以500的余数
            int totalBatchNum = 0;//总批次数
            if (0 == remainder) {
                totalBatchNum = allOrderNum / 500;
            } else {
                totalBatchNum = allOrderNum / 500 + 1;
            }
            for(int i = 0; i < allOrderNum; i += 500){
                if(i + 500 > allOrderNum){        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                    toIndex = allOrderNum - i;
                }
                currentBatchNum ++;
                List<MarketOrderApply> newList = marketOrderApplyList.subList(i, i + toIndex);
                jdInvoiceSubmit(newList, token, currentBatchNum, totalBatchNum, allOrderPrice.toString(), marketId, sysplugin);
            }
        }
    }

    /**
     * 京东订单申请开票
     * @param marketOrderApplyList 子订单列表信息
     * @param token
     * @param currentBatchNum 当前批次号
     * @param totalBatchNum 总批次号
     * @param totalBatchAmount 总批次开发票价税合计
     * @param marketId 结算单号与申请单号
     * @param sysplugin
     */
    public void jdInvoiceSubmit(List<MarketOrderApply> marketOrderApplyList, String token, int currentBatchNum, int totalBatchNum, String totalBatchAmount, String marketId, SysPlugin sysplugin){
        StringBuffer jdOrderIds = new StringBuffer();//所有京东子订单
        BigDecimal batchPrice = new BigDecimal(0);//当前批次含税总金额
        for (int i = 0; i < marketOrderApplyList.size(); i ++) {
            if (marketOrderApplyList.size() -1 == i) {
                jdOrderIds.append(marketOrderApplyList.get(i).getJdOrder());
            } else {
                jdOrderIds.append(marketOrderApplyList.get(i).getJdOrder() + ",");
            }
            batchPrice.add(marketOrderApplyList.get(i).getInvoicePrice());
        }
        String supplierOrder = jdOrderIds.toString();//子订单号，批量以英文逗号分割
        String markId = marketId;//第三方申请单号：申请发票的唯一id标识 (该标记下可以对应多张发票信息)
        String settlementId = marketId;//结算单号（一个结算单号可对对应多个第三方申请单号）
        Integer invoiceType = 2;//发票类型 增值税专用发票 3：电子发票
        Integer invoiceOrg = 544;//开票机构ID
        Integer bizInvoiceContent = 1;//开票内容：1, "明细"； 100, "大类"
        String invoiceDate = DateUtils.getTimeStr(new Date(), DateUtils.HYPHEN_DISPLAY_DATE).substring(0, 10);
        String title = sysplugin.getAttribute("companyName");//发票抬头
        String billToParty = sysplugin.getAttribute("companyName");//收票单位 
        String enterpriseTaxpayer = sysplugin.getAttribute("regCode");//纳税人识别号
        String billToer = sysplugin.getAttribute("invoiceName");//收票人 （专票必须）
        String billToContact = sysplugin.getAttribute("invoicePhone");//收票人联系电话
        Integer billToProvince = Integer.valueOf(sysplugin.getAttribute("invoiceProvice"));//收票人地址（省）  （专票必须）
        Integer billToCity = Integer.valueOf(sysplugin.getAttribute("invoiceCity"));//收票人地址（市）  （专票必须）
        Integer billToCounty = Integer.valueOf(sysplugin.getAttribute("invoiceCounty"));//收票人地址（区）  （专票必须）
        Integer billToTown = Integer.valueOf(sysplugin.getAttribute("invoiceTown"));//收票人地址（街道）（专票有四级地址则必传，否则传0）
        String billToAddress = sysplugin.getAttribute("invoiceAddress");//收票人地址（详细地址）（专票必须）
        int invoiceNum = marketOrderApplyList.size();//当前批次子订单总数
        String invoicePrice = batchPrice.toString();//当前批次含税总金额---BigDecimal
        Integer currentBatch = currentBatchNum;//当前批次号
        Integer totalBatch = totalBatchNum;//总批次数
        String totalBatchInvoiceAmount = totalBatchAmount;//总批次开发票价税合计---BigDecimal
        Integer billingType = 1;//1-集中开票，2-分别开票
        Integer isMerge = 1;//合并开票，（不传默认为合并开票）1-合并SKU，空和其他-分别开票
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("supplierOrder", supplierOrder);//子订单号
        params.put("markId", markId);//第三方申请单号
        params.put("settlementId", settlementId);//结算单号
        params.put("invoiceType", invoiceType);//发票类型
        params.put("invoiceOrg", invoiceOrg);//开票机构ID
        params.put("bizInvoiceContent", bizInvoiceContent);//开票内容
        params.put("invoiceDate", invoiceDate);//期望开票时间
        params.put("title", title);//发票抬头
        params.put("billToParty", billToParty);//收票单位
        params.put("enterpriseTaxpayer", enterpriseTaxpayer);//纳税人识别号
        params.put("billToer", billToer);//收票人
        params.put("billToContact", billToContact);//收票人联系电话
        params.put("billToProvince", billToProvince);//收票人地址（省）
        params.put("billToCity",billToCity );//收票人地址（市）
        params.put("billToCounty", billToCounty);//收票人地址（区）
        params.put("billToTown", billToTown);//收票人地址（街道）
        params.put("billToAddress", billToAddress);//收票人地址
        params.put("invoiceNum", invoiceNum);//当前批次子订单总数
        params.put("invoicePrice", invoicePrice);//当前批次含税总金额
        params.put("currentBatch", currentBatch);//当前批次号
        params.put("totalBatch", totalBatch);//总批次数
        params.put("totalBatchInvoiceAmount", totalBatchInvoiceAmount);//总批次开发票价税合计
        params.put("billingType", billingType);//1-集中开票，2-分别开票
        params.put("isMerge", isMerge);//合并开票
        //申请开票
        Map<String, Object> resultServiceMap = JDServiceUtils.submitInvoice(token, params);
        if ("0004".equals(resultServiceMap.get("resultCode").toString())) {
            for (MarketOrderApply m :marketOrderApplyList) {
                m.setMarkid(marketId);
                m.setState(true);
                marketOrderApplyMapper.updateByPrimaryKey(m);
            }
        } else {
            SysMsgPush sysMsgPush = new SysMsgPush();
            sysMsgPush.setId(CodeGenerator.getUUID());
            sysMsgPush.setIsPush(false);
            sysMsgPush.setMsgLevel(3);
            sysMsgPush.setMsgType(4);
            sysMsgPush.setReadStatus("2");
            sysMsgPush.setPushStatus("0");
            sysMsgPush.setMchId(sysplugin.getMchId());
            sysMsgPush.setSendDate(new Date());
            sysMsgPush.setSendUserId("system");
            sysMsgPush.setSendUserName("admin");
            sysMsgPush.setReceiveUserName("system");
            sysMsgPush.setReceiveUserId("yunyin");
            sysMsgPush.setIsAttac("0");
            Map<String,Object> content = new HashMap<>();
            content.put("title", "京东订单申请发票出错");
            content.put("msg", "京东订单申请发票出错，请求参数为:" + params);
            content.put("supplierName", "京东");
            if (resultServiceMap.containsKey("resultCode")) {
                content.put("applyResult", resultServiceMap.get("resultCode").toString() + "," + resultServiceMap.get("resultMessage").toString());
            } else {
                content.put("applyResult", resultServiceMap.get("resultMessage").toString());
            }
            sysMsgPush.setMsgKey("msg-jingdongMoudle");
            sysMsgPush.setMsgContent(JSON.toJSONString(content));
            sysMsgPush.setMsgTitle(content.get("title").toString());
            sysMsgPushService.insert(sysMsgPush);
        }
    }

}
